package com.ffyc.resale.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ffyc.resale.dao.ChatDao;
import com.ffyc.resale.model.Chat;
import com.ffyc.resale.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ChatService {
    @Autowired
    ChatDao chatDao;

    public List<Chat> getChatList(String userToken) {
        Integer id = JWTUtil.id(userToken);
        List<Chat> list = chatDao.getChatList(id);
        return list;
    }

    public List<Chat> chatRecord(String userToken, Integer id1) {
        Integer id2 = JWTUtil.id(userToken);
        QueryWrapper<Chat> wrapper = new QueryWrapper<Chat>()
                .and(wq -> wq.eq("sender", id1).eq("receiver", id2))
                .or(wq -> wq.eq("sender", id2).eq("receiver", id1))
                .orderByAsc("time");
        List<Chat> chats = chatDao.selectList(wrapper);
        return chats;
    }

    public void createChat(Chat chat, Integer id) {
        chat.setSender(id);
        chat.setContent("你好");
        chat.setTime(new Date());
        chatDao.insert(chat);
    }

    public Page<Chat> selectPage(Integer pageNum,Integer pageSize,String content) {
        Page<Chat> c = new Page<>(pageNum,pageSize);
        QueryWrapper<Chat> queryWrapper = new QueryWrapper<>();
        if(content.length()==0) {
            queryWrapper.like("content", content);
        }
            Page<Chat> chatPage = chatDao.selectPage(c, queryWrapper);
            return chatPage;

    }

    public void deleteById(Integer id) {
        Chat chat = new Chat();
        chat.setId(id);
        chatDao.deleteById(chat);
    }
}
